﻿using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
using WebPart = System.Web.UI.WebControls.WebParts.WebPart;

namespace ITSP.SharePoint.CacheRefresh.Examples.WebParts.SharePriceWebPart
{
    [ToolboxItemAttribute(false)]
    [System.Runtime.InteropServices.Guid("a1dd1248-a203-4353-884e-563b4f3d23f5")]
    public class SharePriceWebPart : WebPart
    {
        #region -- Web Part Properties --

        /// <summary>
        /// Allows the user to select the Stock.
        /// </summary>
        /// <value>The blog site.</value>
        [Category("SharePrice Configuration")]
        [DefaultValue("MSFT")]
        [Personalizable(PersonalizationScope.Shared)]
        [FriendlyName("Stock Name")]
        [WebBrowsable(true)]
        public string StockName { get; set; }

        /// <summary>
        /// Allows the user to select the Stock.
        /// </summary>
        /// <value>The blog site.</value>
        [Category("SharePrice Configuration")]
        [DefaultValue("http://finance.yahoo.com/d/quotes.csv?s={0}&f=nd1l1")]
        [Personalizable(PersonalizationScope.Shared)]
        [FriendlyName("Stock Service Url")]
        [WebBrowsable(true)]
        public string StockServiceUrl { get; set; }

        #endregion

        #region -- Controls

        private Button btnGetStockPrice;
        private Label lblStockPriceHeader;
        private TextBox txtStockName;
        private Label lblStockPriceResult;
        private Label lblStockPriceName;
        private Literal lblErrorMessage;

        #endregion

        private SharePriceCacheManager _cacheManager;
        //private static ILogger _logger = SharePointServiceLocator.GetCurrent().GetInstance<ILogger>();

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            SPSite site = SPContext.Current.Site;
            SPWebApplication webApp = site.WebApplication;
            SPSite rootSite = webApp.Sites[0];
            _cacheManager = new SharePriceCacheManager(rootSite.Url);
        }

        /// <summary>
        /// Create the web part's controls
        /// </summary>
        protected override void CreateChildControls()
        {
            try
            {
                lblStockPriceHeader = new Label();
                lblStockPriceHeader.Text = String.Format("Stock Service Url: {0}", this.StockServiceUrl);
                lblStockPriceHeader.ID = "lblStockPriceHeader";
                Controls.Add(lblStockPriceHeader);

                Controls.Add(new HtmlGenericControl("br"));

                lblStockPriceName = new Label();
                lblStockPriceName.Text = String.Format("Stock Name");
                lblStockPriceName.ID = "lblStockPriceName";
                Controls.Add(lblStockPriceName);

                txtStockName = new TextBox();
                txtStockName.ID = "txtStockName";
                txtStockName.Text = this.StockName;

                Controls.Add(txtStockName);
                Controls.Add(new HtmlGenericControl("br"));

                btnGetStockPrice = new Button();
                btnGetStockPrice.ID = "btnGetStockPrice";
                btnGetStockPrice.Click += new EventHandler(OnGetStockPriceClick);
                btnGetStockPrice.Text = "Get Stock Price";
                Controls.Add(btnGetStockPrice);

                Controls.Add(new HtmlGenericControl("br"));

                lblStockPriceResult = new Label();
                lblStockPriceResult.ID = "lblStockPriceResult";
                Controls.Add(lblStockPriceResult);
                Controls.Add(new HtmlGenericControl("br"));

                lblErrorMessage=new Literal();
                lblErrorMessage.ID = "errorMessage";
                Controls.Add(lblErrorMessage);

                if(!Page.IsPostBack)
                {
                    PopulateSharePriceValue();
                }


            }
            catch (Exception ex)
            {

                throw;
            }
        }

        /// <summary>
        /// Get the Stock Price.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        public void OnGetStockPriceClick(object sender, EventArgs args)
        {
            EnsureChildControls();

            Button button = sender as Button;
            if (button != null)
            {
                PopulateSharePriceValue();
            }

        }

        /// <summary>
        /// Populate the SharePrice Value
        /// </summary>
        private void PopulateSharePriceValue()
        {
            using (SPMonitoredScope scope = new SPMonitoredScope("SharePriceWebPart::PopulateSharePriceValue"))
            {
                try
                {

                    SharePrice sharePriceResult = _cacheManager.Load<SharePrice>(this.StockName);
                    if (sharePriceResult == null)
                    {
                        SharePriceClient client = new SharePriceClient(this.StockServiceUrl);
                        sharePriceResult = client.GetSharePrice(this.StockName);
                        _cacheManager.Save(sharePriceResult, this.StockName);
                    }

                    lblStockPriceResult.Text = String.Format("{0} Trade Value: {1} Last Modified:{2} {3}",
                                                             sharePriceResult.Name, sharePriceResult.LastTrade,
                                                             sharePriceResult.LastModified.ToLongDateString(),
                                                             sharePriceResult.LastModified.ToShortTimeString());
                }
                catch (Exception ex)
                {
                    HandleError(ex);
                }
            }

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="ex"></param>
        private void HandleError(Exception ex)
        {
            try
            {
                if (lblErrorMessage != null)
                {
                    lblErrorMessage.Text = ex.Message;
                }
                //_logger.TraceToDeveloper(ex, 0, TraceSeverity.High, Common.Constants.Logging.DefaultLoggingCategory);
            }
            catch (Exception exex)
            {
                //_logger.TraceToDeveloper(exex,0,TraceSeverity.High, Common.Constants.Logging.DefaultLoggingCategory);
            }
        }
    }

}
